<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/13
 * Time: 10:26
 */

namespace Platform\System\Tools\Upload;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use Platform\System\Tools\ResultTool;

abstract class UploadsManager {

    /**
     * @var string $model 当前模块
     */
    protected $model;

    /**
     * @var array $config 当前模块总配置
     */
    protected $config;

    /**
     * @var object $disk Storage 对象
     */
    protected $disk;

    public function __construct() {
        $this->model = $this->model();
        $this->config = config('upload');
        $this->disk = Storage::disk($this->config['disk']);
    }

    abstract function model();

    /**
     * 保存图片
     * @param Request $request
     * @return array
     */
    public function uploadImg(Request $request){

        $use_type = $request->get('use_type','');
        $files = $request->file('file');

        if (!$files) myResult()->stop(ResultTool::CODE_PARAM_LOST,'未找到文件');
        if (!$use_type) myResult()->stop(ResultTool::CODE_PARAM_LOST,'请指定图片用途');
        if (!$this->checkUseType($use_type)) myResult()->stop(ResultTool::CODE_NO_RIGHT);

        $data = [
            'use_type' => $use_type,
            'count_total' => 1,
            'count_success' => 0,
            'count_failed' => 0,
            'data' => [],
        ];
        if (is_array($files)){
            $data['count_total'] = count($files);

            $save_path = $this->config['img_info'][$use_type]['path'] ?? 'tmp';
            foreach ($files as $key => $file){

                $path = $file->store($save_path,$this->config['disk']);
                $path = $this->pressImg($path,$this->config['disk']);
                if ($path){
                    $data['count_success'] += 1;
                    $upload_res[] = [
                        'path' => $path,
                        'url' => $this->disk->url($path),
                    ];
                }
            }
            $data['data'] = $upload_res;
            $data['count_failed'] = $data['count_total'] - $data['count_success'];
        }else{
            $save_path = $this->config['img_info'][$use_type]['path'] ?? 'tmp';
            $path = $files->store($save_path,$this->config['disk']);
            $path = $this->pressImg($path,$this->config['disk']);
            if ($path){
                $data['count_success'] += 1;
                $data['data'][] = [
                    'path' => $path,
                    'url' => $this->disk->url($path),
                ];
            }
        }

        return $data;
    }

    /**
     * 检查是否可以上传此类图片
     * @param $use_type
     * @return bool
     */
    public function checkUseType($use_type){
        if ($this->model == 'admin') return true;
        return in_array($use_type, $this->config['auth'][$this->model]);
    }

    /**
     * 压缩图片函数
     * @param string $path 相对路径
     * @param string $filesystem 文件系统
     * @param int $quality 质量
     * @param null $width 宽度
     * @param string $encode 编码格式
     * @return string
     */
    public function pressImg($path, $filesystem = 'public', $encode = 'jpg', $quality = 80,$width = null){
        $filepath = Storage::disk($filesystem)->path($path);
        $new_path = str_ireplace(strrchr($path,'.'),'',$path).'.'.$encode;
        $savepath = Storage::disk($filesystem)->path($new_path);
        $img = Image::make($filepath);
        if ($width){
            $img->resize($width, null, function($constraint){		// 调整图像的宽到 $width，并约束宽高比(高自动)
                $constraint->aspectRatio();
            });
        }
        Storage::disk($filesystem)->delete($path);
        $img->save($savepath,$quality);
        return $new_path;
    }
}